package com.irany;

import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.dialect.PropsUtil;
import com.irany.component.ICollector;
import com.irany.model.UserInfo;
import com.irany.util.SeleniumUtils;
import org.openqa.selenium.WebDriver;

import java.util.ArrayList;
import java.util.List;


/**
 * @author shujian.ou
 * @since 2021/5/17 0017 15:25
 */
public abstract class App {

    /**
     * app.properties配置文件
     */
    protected Props appProps;

    /**
     * webdriver实例
     */
    protected WebDriver driver;

    /**
     * APP域内的用户信息,用于登录
     */
    protected UserInfo userInfo;

    /**
     * 爬虫名称,作为唯一标识用于缓存webdriver
     */
    protected String appName;

    private final List<ICollector> collectors = new ArrayList<>();

    public static void main(String[] args) {
        try {
            JiraApp jiraApp = new JiraApp("jira");
            jiraApp.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean run() throws Exception {
        boolean logon = login();
        if (logon) {
            collectors.forEach(ICollector::run);
        }
        destroy();
        return logon;
    }

    protected void destroy() {
        driver.quit();
        SeleniumUtils.removeDriver(this.appName);
    }

    protected void initProp() {
        appProps = PropsUtil.get("app");
        userInfo = new UserInfo();
        userInfo.setUsername(appProps.getStr("app.username"));
        userInfo.setPassword(appProps.getStr("app.password"));

    }

    public void addCollector(ICollector collector) {
        collectors.add(collector);
    }

    public boolean isFirstRun() {
        return getAppProps().getBool("app.isFirst");
    }

    public String getAppName() {
        return appName;
    }

    public WebDriver getDriver() {
        return driver;
    }

    public Props getAppProps() {
        return appProps;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    protected abstract boolean login() throws Exception;

}
